<?php
namespace Modules\Frontend\Controllers;

class UserMessageController extends \Phalcon\Mvc\Controller {
	public function beforeExecuteRoute() {
		\Components\Utils::isClosedFrontent($this);
	}

	public function initialize() {
		$this -> response -> setStatusCode(200, 'OK') -> sendHeaders() -> setContentType('application/json', 'UTF-8');
	}

	public function pagerAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}

		if(!isset($query['page'])) {
			$query['page'] = 1;
		} else if($query['page'] <= 0)  {
			$query['page'] = 1;
		} else {
			$query['page'] = abs($query['page']);
		}

		if(!isset($query['limit'])) {
			$query['limit'] = 10;
		} else if($query['limit'] <= 0)  {
			$query['limit'] = 10;
		} else {
			$query['limit'] = abs($query['limit']);
		}

		$service = $this -> account::getMessageServiceInstance() -> pager([
			'conditions' => 'um.user_id = ' . $serviceUser['user'] -> user_id,
			'order' => 'reply_time DESC, message_id DESC'
		], $query['limit'], $query['page']);

		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'Success', 'pager' => $service['pager']]);
	}

	public function createAction() {
		$serviceUser = $this -> account::getServiceInstance() -> checkLogin($this -> request -> getQuery('token', 'string', null));
		if($serviceUser['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$serviceUser['code'],'msg'=>$serviceUser['message']]);
		}
		
		$post = $this -> request -> getPost();
		$service = $this -> account::getMessageServiceInstance() -> create([
			'user_id' => $serviceUser['user'] -> user_id,
			'title' => $post['title'],
			'content' => $post['content'],
			'create_time' => time(),
			'reply_time' => 0,
			'status' => 1
		]);
		if($service['code'] != 0) {
			return $this -> response -> setJsonContent(['code'=>$service['code'],'msg'=>$service['message']]);
		}
		return $this -> response -> setJsonContent(['code'=>0,'msg'=>'添加成功']);
	}
}